#include "socket.hpp"
#include <pthread.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

void Usage(const std::string& proc)
{
    cout << "you can use " << proc << " port " << endl;
}

void* handler_request(void* args)
{
    pthread_detach(pthread_self());
    int sock = *(int*)args;
    delete (int*)args;

    //业务逻辑
#define NUM 1024*10
    char buffer[NUM] = {0};
    ssize_t ret = recv(sock, buffer, sizeof(buffer), 0);
    if(ret > 0)
    {
        buffer[NUM] = 0;
        cout << buffer;
        //构建响应

        // string send_string;
        // send_string += "HTTP/1.1 404 Not Found\n";
        // send_string += "Content-Type: text/html;charset=UTF-8\n";
        // send_string += "\n";
        // send_string += "你要访问的资源不存在！\n";
        
        // send_string += "HTTP/1.1 404 Not Found\n";
        // send_string += "Content-Type: text/html;charset=UTF-8\n";
        // send_string += "\n";
        // send_string += "<html><p>你要访问的资源不存在</p></html>\n";
        // send_string += "Set-Cookie: username=loj\n";
        // send_string += "Set-Cookie: password=657575\n";
        // send_string += "Location: https://www.qq.com/\n";
        //send_string += "\n";
        
        //send_string += "hello, 你好！\n";
        string html_file = "./wwwroot/index.html";
        ifstream in(html_file);

        if(in.is_open())
        {
            struct stat st;
            stat(html_file.c_str(), &st);
            string send_string;
            send_string += "HTTP/1.1 200 OK\n";
            send_string += "Content-Type: text/html;charset=UTF-8\n";
            send_string += "Content-Length: ";
            send_string += to_string(st.st_size);
            send_string += "\n";
            send_string += "\n";
            string s;
            while(getline(in, s))
            {
                send_string += s;
            }
            send(sock, send_string.c_str(), send_string.length(), 0);
        }
        else
        {
            cerr << "open error " << endl;
        }
        in.close();
        close(sock);
    }
    return nullptr;
}
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, atoi(argv[1]));
    Sock::Listen(listen_sock);
    for(;;)
    {
        int new_sock = Sock::Accept(listen_sock);
        pthread_t tid;
        int* parm = new int(new_sock);
        pthread_create(&tid, nullptr, handler_request, parm);
    }
    
    return 0;
}